package org.example.com.editor.command;

import org.example.com.editor.command.editorCommand.*;
import org.example.com.editor.command.logCommand.LogOffCommand;
import org.example.com.editor.command.logCommand.LogOnCommand;
import org.example.com.editor.command.logCommand.LogShowCommand;
import org.example.com.editor.command.workspaceCommand.*;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;
import org.example.com.editor.logger.LogManager;

import java.util.ArrayList;
import java.util.List;

public class CommandParser {
    // 注册所有命令（后续添加新命令，在这里加即可）
    private final List<Command> commands = new ArrayList<>();


    public CommandParser(LogManager logManager){
        // 注册基础命令
        commands.add(new LoadCommand(logManager));
        commands.add(new SaveCommand(logManager));
        commands.add(new ExitCommand());
        commands.add(new CloseCommand(logManager));
        commands.add(new EditCommand(logManager));
        commands.add(new EditorListCommand());
        commands.add(new InitCommand(logManager));
        commands.add(new DirTreeCommand());
        commands.add(new UndoCommand(logManager));
        commands.add(new RedoCommand(logManager));
        commands.add(new AppendCommand(logManager));
        commands.add(new InsertCommand(logManager));
        commands.add(new DeleteCommand(logManager));
        commands.add(new ReplaceCommand(logManager));
        commands.add(new ShowCommand(logManager));
        commands.add(new LogOnCommand(logManager));
        commands.add(new LogOffCommand(logManager));
        commands.add(new LogShowCommand(logManager));

    }


    // 解析输入并执行命令
    public void parseAndExecute(String input, Workspace workspace, ConsoleUI ui) throws Exception {
        input = input.trim();
        if (input.isEmpty()) return;

        String[] parts = parseArgs(input);
        if (parts.length == 1 && "__UNclosed_QUOTE__".equals(parts[0])) {
            ui.printError("引号未闭合，请检查参数格式（文本需用双引号包裹且闭合）");
            return;
        }
        String commandName = parts[0].toLowerCase();

        for (Command command : commands) {
            if (command.getName().equals(commandName)) {
                ui.setCommandArgs(parts);  // 传递参数给UI（命令需要时获取）
                command.execute(workspace, ui);
                return;
            }
        }

        // 未找到命令
        ui.printError("未知命令：" + commandName + "，输入help查看帮助");
    }

    private String[] parseArgs(String input) {
        List<String> argsList = new ArrayList<>();
        StringBuilder currentArg = new StringBuilder();
        boolean inQuotes = false;

        for (char c : input.trim().toCharArray()) {
            if (c == '"') {
                inQuotes = !inQuotes;
                currentArg.append(c); // 保留引号（供后续命令校验格式）
            } else if (c == ' ' && !inQuotes) {
                if (!currentArg.isEmpty()) {
                    argsList.add(currentArg.toString());
                    currentArg.setLength(0);
                }
            } else {
                currentArg.append(c);
            }
        }

        // 处理最后一个参数
        if (!currentArg.isEmpty()) {
            argsList.add(currentArg.toString());
        }

        // 引号未闭合：返回长度为1的数组，用特殊标记表示
        if (inQuotes) {
            return new String[]{"__UNclosed_QUOTE__"}; // 自定义标记，避免与命令名冲突
        }

        // 正常情况：返回解析后的参数数组
        return argsList.isEmpty() ? new String[0] : argsList.toArray(new String[0]);
    }

}